<?php
namespace app\Controller;

use app\Model\User;
use app\Model\Album;
use lib\View;

class AuthenticateController
{
	public function register()
	{
		$errorBag = isset($_SESSION['errorBag']) ? $_SESSION['errorBag'] : ['id' => '', 'email' => '', 'userName' => '', 'password' => '', 'pwdConfirm' => ''];
		$inputBag = isset($_SESSION['inputBag']) ? $_SESSION['inputBag'] : ['id' => '', 'email' => '', 'userName' => ''];

		// 销毁session中的错误数据包 （错误数据包是一次性的）
	   unset($_SESSION['inputBag']);
	   unset($_SESSION['errorBag']);

	   return $this->view('auth/register', ['errorBag' => $errorBag, 'inputBag' => $inputBag]);
	}

	public function registerAction()
	{
		$user = User::newUser($_POST);
		if (empty($user)) {
			header('Location:' . url('auth/register?op=1'));
			return;
		}

		$user->password = password_hash($user->password, PASSWORD_BCRYPT);

		$user->save();
		header('Location:' . url('auth/register?op=2'));
	}

	public function login()
	{
		$errorBag = isset($_SESSION['errorBag']) ? $_SESSION['errorBag'] : ['email' => '', 'password' => ''];

		// 销毁session中的错误数据包 （错误数据包是一次性的）
   		unset($_SESSION['errorBag']);

   		// return $this->view('auth/signin', ['errorBag' => $errorBag]);
	}

	public function loginAction()
	{
		$email = $_POST['email'];
		$password = $_POST['password'];
		$user = User::find(['email' => $email]);

		if (!empty($user)) {
		  if (password_verify($password, $user->password)) {
		    $_SESSION['user'] = $user;
		    
		    header('Location:' . url('index'));
		    return;
		  }
		}

		$_SESSION['errorBag'] = ['email' => '邮箱错误', 'password' => '密码错误'];
		header('Location:' . url('auth/register?op=2'));
	}

	private function view($viewName, $data = [])
	{
		return new View($viewName, $data);
	}
}